<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>perlfaq6 - Regular Expressions - Perldoc Browser</title>
    <link rel="search" href="https://perldoc.perl.org/opensearch.xml" type="application/opensearchdescription+xml" title="Perldoc Browser">
    <link rel="canonical" href="https://perldoc.perl.org/perlfaq6">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.5.0/styles/stackoverflow-light.min.css" integrity="sha512-cG1IdFxqipi3gqLmksLtuk13C+hBa57a6zpWxMeoY3Q9O6ooFxq50DayCdm0QrDgZjMUn23z/0PMZlgft7Yp5Q==" crossorigin="anonymous" />
    <style>
      body {
        background: #f4f4f5;
        color: #020202;
      }
      .navbar-dark {
        background-image: -webkit-linear-gradient(top, #005f85 0, #002e49 100%);
        background-image: -o-linear-gradient(top, #005f85 0, #002e49 100%);
        background-image: linear-gradient(to bottom, #005f85 0, #002e49 100%);
        filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff005f85', endColorstr='#ff002e49', GradientType=0);
        background-repeat: repeat-x;
      }
      .navbar-dark .navbar-nav .nav-link,
      .navbar-dark .navbar-nav .nav-link:focus { color: #fff }
      .navbar-dark .navbar-nav .nav-link:hover { color: #ffef68 }
      #wrapperlicious {
        margin: 0 auto;
        font: 0.9em 'Helvetica Neue', Helvetica, sans-serif;
        font-weight: normal;
        line-height: 1.5em;
        margin: 0;
        padding: 0;
      }
      #wrapperlicious h1 { font-size: 1.5em }
      #wrapperlicious h2 { font-size: 1.3em }
      #wrapperlicious h3 { font-size: 1.1em }
      #wrapperlicious h4 { font-size: 0.9em }
      #wrapperlicious h1, #wrapperlicious h2, #wrapperlicious h3,
      #wrapperlicious h4, #wrapperlicious dt {
        color: #020202;
        margin-top: 1em;
        margin-bottom: 1em;
        position: relative;
        font-weight: bold;
      }
      #wrapperlicious a { color: inherit; text-decoration: underline }
      #wrapperlicious #toc { text-decoration: none }
      #wrapperlicious a:hover { color: #2a2a2a }
      #wrapperlicious a img { border: 0 }
      #wrapperlicious :not(pre) > code {
        color: inherit;
        background-color: rgba(0, 0, 0, 0.04);
        border-radius: 3px;
        font: 0.9em Consolas, Menlo, Monaco, monospace;
        padding: 0.3em;
      }
      #wrapperlicious dd {
        margin: 0;
        margin-left: 2em;
      }
      #wrapperlicious dt {
        color: #2a2a2a;
        font-weight: bold;
        margin-left: 0.9em;
      }
      #wrapperlicious p {
        margin-bottom: 1em;
        margin-top: 1em;
      }
      #wrapperlicious li > p {
        margin-bottom: 0;
        margin-top: 0;
      }
      #wrapperlicious pre {
        border: 1px solid #c1c1c1;
        border-radius: 3px;
        font: 100% Consolas, Menlo, Monaco, monospace;
        margin-bottom: 1em;
        margin-top: 1em;
      }
      #wrapperlicious pre > code {
        display: block;
        background-color: #f6f6f6;
        font: 0.9em Consolas, Menlo, Monaco, monospace;
        line-height: 1.5em;
        text-align: left;
        white-space: pre;
        padding: 1em;
      }
      #wrapperlicious dl, #wrapperlicious ol, #wrapperlicious ul {
        margin-bottom: 1em;
        margin-top: 1em;
      }
      #wrapperlicious ul {
        list-style-type: square;
      }
      #wrapperlicious ul ul {
        margin-bottom: 0px;
        margin-top: 0px;
      }
      #footer {
        font-size: 0.8em;
        padding-top: 0.5em;
        text-align: center;
      }
      #more {
        display: inline;
        font-size: 0.8em;
      }
      #perldocdiv {
        background-color: #fff;
        border: 1px solid #c1c1c1;
        border-bottom-left-radius: 5px;
        border-bottom-right-radius: 5px;
        margin-left: auto;
        margin-right: auto;
        padding: 3em;
        padding-top: 1em;
        max-width: 960px;
      }
      #moduleversion { float: right }
      #wrapperlicious .leading-notice {
        font-style: italic;
        padding-left: 1em;
        margin-top: 1em;
        margin-bottom: 1em;
      }
      #wrapperlicious .permalink {
        display: none;
        left: -0.75em;
        position: absolute;
        padding-right: 0.25em;
        text-decoration: none;
      }
      #wrapperlicious h1:hover .permalink, #wrapperlicious h2:hover .permalink,
      #wrapperlicious h3:hover .permalink, #wrapperlicious h4:hover .permalink,
      #wrapperlicious dt:hover .permalink {
        display: block;
      }
    </style>
    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=G-KVNWBNT5FB"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());

      gtag('config', 'G-KVNWBNT5FB');
      gtag('config', 'UA-50555-3');
    </script>
  </head>
  <body>
    <nav class="navbar navbar-expand-md navbar-dark bg-dark justify-content-between">
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <a class="navbar-brand" href="https://perldoc.perl.org/">Perldoc Browser</a>
  <div class="collapse navbar-collapse" id="navbarNav">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item dropdown text-nowrap">
        <a class="nav-link dropdown-toggle" href="perlfaq6.html#" id="dropdownlink-stable" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">5.35.0</a>
        <div class="dropdown-menu" aria-labelledby="dropdownlink-stable">
          <a class="dropdown-item" href="https://perldoc.perl.org/perlfaq6">Latest</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.2/perlfaq6">5.38.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.1/perlfaq6">5.38.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.0/perlfaq6">5.38.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.3/perlfaq6">5.36.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.2/perlfaq6">5.36.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.1/perlfaq6">5.36.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.0/perlfaq6">5.36.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.3/perlfaq6">5.34.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.2/perlfaq6">5.34.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.1/perlfaq6">5.34.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.0/perlfaq6">5.34.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.32.1/perlfaq6">5.32.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.32.0/perlfaq6">5.32.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.3/perlfaq6">5.30.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.2/perlfaq6">5.30.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.1/perlfaq6">5.30.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.0/perlfaq6">5.30.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.3/perlfaq6">5.28.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.2/perlfaq6">5.28.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.1/perlfaq6">5.28.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.0/perlfaq6">5.28.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.3/perlfaq6">5.26.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.2/perlfaq6">5.26.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.1/perlfaq6">5.26.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.0/perlfaq6">5.26.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.4/perlfaq6">5.24.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.3/perlfaq6">5.24.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.2/perlfaq6">5.24.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.1/perlfaq6">5.24.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.0/perlfaq6">5.24.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.4/perlfaq6">5.22.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.3/perlfaq6">5.22.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.2/perlfaq6">5.22.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.1/perlfaq6">5.22.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.0/perlfaq6">5.22.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.3/perlfaq6">5.20.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.2/perlfaq6">5.20.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.1/perlfaq6">5.20.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.0/perlfaq6">5.20.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.4/perlfaq6">5.18.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.3/perlfaq6">5.18.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.2/perlfaq6">5.18.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.1/perlfaq6">5.18.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.0/perlfaq6">5.18.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.3/perlfaq6">5.16.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.2/perlfaq6">5.16.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.1/perlfaq6">5.16.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.0/perlfaq6">5.16.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.4/perlfaq6">5.14.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.3/perlfaq6">5.14.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.2/perlfaq6">5.14.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.1/perlfaq6">5.14.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.0/perlfaq6">5.14.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.5/perlfaq6">5.12.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.4/perlfaq6">5.12.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.3/perlfaq6">5.12.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.2/perlfaq6">5.12.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.1/perlfaq6">5.12.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.0/perlfaq6">5.12.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.10.1/perlfaq6">5.10.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.10.0/perlfaq6">5.10.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.9/perlfaq6">5.8.9</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.8/perlfaq6">5.8.8</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.7/perlfaq6">5.8.7</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.6/perlfaq6">5.8.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.5/perlfaq6">5.8.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.4/perlfaq6">5.8.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.3/perlfaq6">5.8.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.2/perlfaq6">5.8.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.1/perlfaq6">5.8.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.0/perlfaq6">5.8.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.6.2/perlfaq6">5.6.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.6.1/perlfaq6">5.6.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.6.0/perlfaq6">5.6.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_04/perlfaq6">5.005_04</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_03/perlfaq6">5.005_03</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_02/perlfaq6">5.005_02</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_01/perlfaq6">5.005_01</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005/perlfaq6">5.005</a>
        </div>
      </li>
      <li class="nav-item dropdown text-nowrap">
        <a class="nav-link dropdown-toggle" href="perlfaq6.html#" id="dropdownlink-dev" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dev</a>
        <div class="dropdown-menu" aria-labelledby="dropdownlink-dev">
          <a class="dropdown-item" href="https://perldoc.perl.org/blead/perlfaq6">blead</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.6/perlfaq6">5.39.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.5/perlfaq6">5.39.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.4/perlfaq6">5.39.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.3/perlfaq6">5.39.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.2/perlfaq6">5.39.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.1/perlfaq6">5.39.1</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.0-RC2/perlfaq6">5.38.0-RC2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.0-RC1/perlfaq6">5.38.0-RC1</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.11/perlfaq6">5.37.11</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.10/perlfaq6">5.37.10</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.9/perlfaq6">5.37.9</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.8/perlfaq6">5.37.8</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.7/perlfaq6">5.37.7</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.6/perlfaq6">5.37.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.5/perlfaq6">5.37.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.4/perlfaq6">5.37.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.3/perlfaq6">5.37.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.2/perlfaq6">5.37.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.1/perlfaq6">5.37.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.0/perlfaq6">5.37.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.11/perlfaq6">5.35.11</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.10/perlfaq6">5.35.10</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.9/perlfaq6">5.35.9</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.8/perlfaq6">5.35.8</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.7/perlfaq6">5.35.7</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.6/perlfaq6">5.35.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.5/perlfaq6">5.35.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.4/perlfaq6">5.35.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.3/perlfaq6">5.35.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.2/perlfaq6">5.35.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.1/perlfaq6">5.35.1</a>
          <a class="dropdown-item active" href="perlfaq6.html">5.35.0</a>
        </div>
      </li>
      <li class="nav-item dropdown text-nowrap">
        <a class="nav-link dropdown-toggle" href="perlfaq6.html#" id="dropdownlink-nav" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Documentation</a>
        <div class="dropdown-menu" aria-labelledby="dropdownlink-nav">
          <a class="dropdown-item" href="perl.html">Perl</a>
          <a class="dropdown-item" href="perlintro.html">Intro</a>
          <a class="dropdown-item" href="perl.html#Tutorials">Tutorials</a>
          <a class="dropdown-item" href="perlfaq.html">FAQs</a>
          <a class="dropdown-item" href="perl.html#Reference-Manual">Reference</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="perlop.html">Operators</a>
          <a class="dropdown-item" href="functions.html">Functions</a>
          <a class="dropdown-item" href="variables.html">Variables</a>
          <a class="dropdown-item" href="modules.html">Modules</a>
          <a class="dropdown-item" href="perlutil.html">Utilities</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="perlcommunity.html">Community</a>
          <a class="dropdown-item" href="perlhist.html">History</a>
        </div>
      </li>
    </ul>
    <ul class="navbar-nav">
      <script>
        function set_expand (expand) {
          var perldocdiv = document.getElementById('perldocdiv');
          var width = window.getComputedStyle(perldocdiv).getPropertyValue('max-width');
          var expanded = (width == '' || width == 'none') ? true : false;
          if (expand === null) {
            expand = !expanded;
          }
          if ((expand && !expanded) || (!expand && expanded)) {
            perldocdiv.style.setProperty('max-width', expand ? 'none' : '960px');
            var button_classlist = document.getElementById('content-expand-button').classList;
            if (expand) {
              button_classlist.add('btn-light');
              button_classlist.remove('btn-outline-light');
            } else {
              button_classlist.add('btn-outline-light');
              button_classlist.remove('btn-light');
            }
          }
          return expand;
        }
        function toggle_expand () {
          var expand = set_expand(null);
          document.cookie = 'perldoc_expand=' + (expand ? 1 : 0) + '; path=/; expires=Tue, 19 Jan 2038 03:14:07 UTC';
        }
        function read_expand () {
          return document.cookie.split(';').some(function (item) { return item.indexOf('perldoc_expand=1') >= 0 });
        }
        if (document.readyState === 'loading') {
          document.addEventListener('DOMContentLoaded', function () {
            if (read_expand()) {
              set_expand(true);
            }
          });
        } else if (read_expand()) {
          set_expand(true);
        }
      </script>
      <button id="content-expand-button" type="button" class="btn btn-outline-light d-none d-lg-inline-block mr-2" onclick="toggle_expand()">Expand</button>
    <ul>
    <form class="form-inline" method="get" action="https://perldoc.perl.org/5.35.0/search">
      <input class="form-control mr-3" type="search" name="q" placeholder="Search" aria-label="Search">
    </form>
  </div>
</nav>

    <div id="wrapperlicious" class="container-fluid">
      <div id="perldocdiv">
        <div id="links">
          <a href="perlfaq6.html">perlfaq6</a>
          <div id="more">
            (<a href="perlfaq6.txt">source</a>,
            <a href="https://metacpan.org/pod/perlfaq6">CPAN</a>)
          </div>
        </div>
        <div class="leading-notice">
          You are viewing the version of this documentation from Perl 5.35.0.
            This is a development version of Perl.
        </div>
        <h1><a id="toc">CONTENTS</a></h1>
                  <ul>
              <li>
                <a class="text-decoration-none" href="perlfaq6.html#NAME">NAME</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq6.html#VERSION">VERSION</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq6.html#DESCRIPTION">DESCRIPTION</a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="perlfaq6.html#How-can-I-hope-to-use-regular-expressions-without-creating-illegible-and-unmaintainable-code?">How can I hope to use regular expressions without creating illegible and unmaintainable code?    </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq6.html#I&#39;m-having-trouble-matching-over-more-than-one-line.-What&#39;s-wrong?">I&#39;m having trouble matching over more than one line. What&#39;s wrong?   </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq6.html#How-can-I-pull-out-lines-between-two-patterns-that-are-themselves-on-different-lines?">How can I pull out lines between two patterns that are themselves on different lines? </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq6.html#How-do-I-match-XML,-HTML,-or-other-nasty,-ugly-things-with-a-regex?">How do I match XML, HTML, or other nasty, ugly things with a regex?       </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq6.html#I-put-a-regular-expression-into-$/-but-it-didn&#39;t-work.-What&#39;s-wrong?">I put a regular expression into $/ but it didn&#39;t work. What&#39;s wrong?   </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq6.html#How-do-I-substitute-case-insensitively-on-the-LHS-while-preserving-case-on-the-RHS?">How do I substitute case-insensitively on the LHS while preserving case on the RHS?    </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq6.html#How-can-I-make-%5Cw-match-national-character-sets?">How can I make \w match national character sets? </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq6.html#How-can-I-match-a-locale-smart-version-of-/%5Ba-zA-Z%5D/?">How can I match a locale-smart version of /[a-zA-Z]/? </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq6.html#How-can-I-quote-a-variable-to-use-in-a-regex?">How can I quote a variable to use in a regex?   </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq6.html#What-is-/o-really-for?">What is /o really for?  </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq6.html#How-do-I-use-a-regular-expression-to-strip-C-style-comments-from-a-file?">How do I use a regular expression to strip C-style comments from a file?</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq6.html#Can-I-use-Perl-regular-expressions-to-match-balanced-text?">Can I use Perl regular expressions to match balanced text?         </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq6.html#What-does-it-mean-that-regexes-are-greedy?-How-can-I-get-around-it?">What does it mean that regexes are greedy? How can I get around it?  </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq6.html#How-do-I-process-each-word-on-each-line?">How do I process each word on each line? </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq6.html#How-can-I-print-out-a-word-frequency-or-line-frequency-summary?">How can I print out a word-frequency or line-frequency summary?</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq6.html#How-can-I-do-approximate-matching?">How can I do approximate matching?  </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq6.html#How-do-I-efficiently-match-many-regular-expressions-at-once?">How do I efficiently match many regular expressions at once?   </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq6.html#Why-don&#39;t-word-boundary-searches-with-%5Cb-work-for-me?">Why don&#39;t word-boundary searches with \b work for me? </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq6.html#Why-does-using-$&amp;,-$%60,-or-$&#39;-slow-my-program-down?">Why does using $&amp;, $`, or $&#39; slow my program down?      </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq6.html#What-good-is-%5CG-in-a-regular-expression?">What good is \G in a regular expression? </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq6.html#Are-Perl-regexes-DFAs-or-NFAs?-Are-they-POSIX-compliant?">Are Perl regexes DFAs or NFAs? Are they POSIX compliant?   </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq6.html#What&#39;s-wrong-with-using-grep-in-a-void-context?">What&#39;s wrong with using grep in a void context? </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq6.html#How-can-I-match-strings-with-multibyte-characters?">How can I match strings with multibyte characters?     </a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq6.html#How-do-I-match-a-regular-expression-that&#39;s-in-a-variable?">How do I match a regular expression that&#39;s in a variable?       </a>
              </li>
          </ul>

              </li>
              <li>
                <a class="text-decoration-none" href="perlfaq6.html#AUTHOR-AND-COPYRIGHT">AUTHOR AND COPYRIGHT</a>
              </li>
          </ul>

      <h1 id="NAME"><a class="permalink" href="perlfaq6.html#NAME">#</a>NAME</h1>

<p>perlfaq6 - Regular Expressions</p>

<h1 id="VERSION"><a class="permalink" href="perlfaq6.html#VERSION">#</a>VERSION</h1>

<p>version 5.20210411</p>

<h1 id="DESCRIPTION"><a class="permalink" href="perlfaq6.html#DESCRIPTION">#</a>DESCRIPTION</h1>

<p>This section is surprisingly small because the rest of the FAQ is littered with answers involving regular expressions. For example, decoding a URL and checking whether something is a number can be handled with regular expressions, but those answers are found elsewhere in this document (in <a href="perlfaq9.html">perlfaq9</a>: &quot;How do I decode or create those %-encodings on the web&quot; and <a href="perlfaq4.html">perlfaq4</a>: &quot;How do I determine whether a scalar is a number/whole/integer/float&quot;, to be precise).</p>

<h2 id="How-can-I-hope-to-use-regular-expressions-without-creating-illegible-and-unmaintainable-code?"><a class="permalink" href="perlfaq6.html#How-can-I-hope-to-use-regular-expressions-without-creating-illegible-and-unmaintainable-code?">#</a><a id="How"></a><a id="How-can-I-hope-to-use-regular-expressions-without-creating-illegible-and-unmaintainable-code"></a>How can I hope to use regular expressions without creating illegible and unmaintainable code?    </h2>

<p>Three techniques can make regular expressions maintainable and understandable.</p>

<dl>

<dt id="Comments-Outside-the-Regex"><a class="permalink" href="perlfaq6.html#Comments-Outside-the-Regex">#</a><a id="Comments"></a>Comments Outside the Regex</dt>
<dd>

<p>Describe what you&#39;re doing and how you&#39;re doing it, using normal Perl comments.</p>

<pre><code># turn the line into the first word, a colon, and the
# number of characters on the rest of the line
s/^(\w+)(.*)/ lc($1) . &quot;:&quot; . length($2) /meg;</code></pre>

</dd>
<dt id="Comments-Inside-the-Regex"><a class="permalink" href="perlfaq6.html#Comments-Inside-the-Regex">#</a><a id="Comments1"></a>Comments Inside the Regex</dt>
<dd>

<p>The <code>/x</code> modifier causes whitespace to be ignored in a regex pattern (except in a character class and a few other places), and also allows you to use normal comments there, too. As you can imagine, whitespace and comments help a lot.</p>

<p><code>/x</code> lets you turn this:</p>

<pre><code>s{&lt;(?:[^&gt;&#39;&quot;]*|&quot;.*?&quot;|&#39;.*?&#39;)+&gt;}{}gs;</code></pre>

<p>into this:</p>

<pre><code>s{ &lt;                    # opening angle bracket
    (?:                 # Non-backreffing grouping paren
        [^&gt;&#39;&quot;] *        # 0 or more things that are neither &gt; nor &#39; nor &quot;
            |           #    or else
        &quot;.*?&quot;           # a section between double quotes (stingy match)
            |           #    or else
        &#39;.*?&#39;           # a section between single quotes (stingy match)
    ) +                 #   all occurring one or more times
    &gt;                   # closing angle bracket
}{}gsx;                 # replace with nothing, i.e. delete</code></pre>

<p>It&#39;s still not quite so clear as prose, but it is very useful for describing the meaning of each part of the pattern.</p>

</dd>
<dt id="Different-Delimiters"><a class="permalink" href="perlfaq6.html#Different-Delimiters">#</a><a id="Different"></a>Different Delimiters</dt>
<dd>

<p>While we normally think of patterns as being delimited with <code>/</code> characters, they can be delimited by almost any character. <a href="perlre.html">perlre</a> describes this. For example, the <code>s///</code> above uses braces as delimiters. Selecting another delimiter can avoid quoting the delimiter within the pattern:</p>

<pre><code>s/\/usr\/local/\/usr\/share/g;    # bad delimiter choice
s#/usr/local#/usr/share#g;        # better</code></pre>

<p>Using logically paired delimiters can be even more readable:</p>

<pre><code>s{/usr/local/}{/usr/share}g;      # better still</code></pre>

</dd>
</dl>

<h2 id="I&#39;m-having-trouble-matching-over-more-than-one-line.-What&#39;s-wrong?"><a class="permalink" href="perlfaq6.html#I&#39;m-having-trouble-matching-over-more-than-one-line.-What&#39;s-wrong?">#</a><a id="I"></a><a id="Im-having-trouble-matching-over-more-than-one-line.-Whats-wrong"></a>I&#39;m having trouble matching over more than one line. What&#39;s wrong?   </h2>

<p>Either you don&#39;t have more than one line in the string you&#39;re looking at (probably), or else you aren&#39;t using the correct modifier(s) on your pattern (possibly).</p>

<p>There are many ways to get multiline data into a string. If you want it to happen automatically while reading input, you&#39;ll want to set $/ (probably to &#39;&#39; for paragraphs or <code>undef</code> for the whole file) to allow you to read more than one line at a time.</p>

<p>Read <a href="perlre.html">perlre</a> to help you decide which of <code>/s</code> and <code>/m</code> (or both) you might want to use: <code>/s</code> allows dot to include newline, and <code>/m</code> allows caret and dollar to match next to a newline, not just at the end of the string. You do need to make sure that you&#39;ve actually got a multiline string in there.</p>

<p>For example, this program detects duplicate words, even when they span line breaks (but not paragraph ones). For this example, we don&#39;t need <code>/s</code> because we aren&#39;t using dot in a regular expression that we want to cross line boundaries. Neither do we need <code>/m</code> because we don&#39;t want caret or dollar to match at any point inside the record next to newlines. But it&#39;s imperative that $/ be set to something other than the default, or else we won&#39;t actually ever have a multiline record read in.</p>

<pre><code>$/ = &#39;&#39;;          # read in whole paragraph, not just one line
while ( &lt;&gt; ) {
    while ( /\b([\w&#39;-]+)(\s+\g1)+\b/gi ) {     # word starts alpha
        print &quot;Duplicate $1 at paragraph $.\n&quot;;
    }
}</code></pre>

<p>Here&#39;s some code that finds sentences that begin with &quot;From &quot; (which would be mangled by many mailers):</p>

<pre><code>$/ = &#39;&#39;;          # read in whole paragraph, not just one line
while ( &lt;&gt; ) {
    while ( /^From /gm ) { # /m makes ^ match next to \n
    print &quot;leading From in paragraph $.\n&quot;;
    }
}</code></pre>

<p>Here&#39;s code that finds everything between START and END in a paragraph:</p>

<pre><code>undef $/;          # read in whole file, not just one line or paragraph
while ( &lt;&gt; ) {
    while ( /START(.*?)END/sgm ) { # /s makes . cross line boundaries
        print &quot;$1\n&quot;;
    }
}</code></pre>

<h2 id="How-can-I-pull-out-lines-between-two-patterns-that-are-themselves-on-different-lines?"><a class="permalink" href="perlfaq6.html#How-can-I-pull-out-lines-between-two-patterns-that-are-themselves-on-different-lines?">#</a><a id="How1"></a><a id="How-can-I-pull-out-lines-between-two-patterns-that-are-themselves-on-different-lines"></a>How can I pull out lines between two patterns that are themselves on different lines? </h2>

<p>You can use Perl&#39;s somewhat exotic <code>..</code> operator (documented in <a href="perlop.html">perlop</a>):</p>

<pre><code class="plaintext">perl -ne &#39;print if /START/ .. /END/&#39; file1 file2 ...</code></pre>

<p>If you wanted text and not lines, you would use</p>

<pre><code>perl -0777 -ne &#39;print &quot;$1\n&quot; while /START(.*?)END/gs&#39; file1 file2 ...</code></pre>

<p>But if you want nested occurrences of <code>START</code> through <code>END</code>, you&#39;ll run up against the problem described in the question in this section on matching balanced text.</p>

<p>Here&#39;s another example of using <code>..</code>:</p>

<pre><code>while (&lt;&gt;) {
    my $in_header =   1  .. /^$/;
    my $in_body   = /^$/ .. eof;
# now choose between them
} continue {
    $. = 0 if eof;    # fix $.
}</code></pre>

<h2 id="How-do-I-match-XML,-HTML,-or-other-nasty,-ugly-things-with-a-regex?"><a class="permalink" href="perlfaq6.html#How-do-I-match-XML,-HTML,-or-other-nasty,-ugly-things-with-a-regex?">#</a><a id="How2"></a><a id="How-do-I-match-XML-HTML-or-other-nasty-ugly-things-with-a-regex"></a>How do I match XML, HTML, or other nasty, ugly things with a regex?       </h2>

<p>Do not use regexes. Use a module and forget about the regular expressions. The <a href="./XML::LibXML.html">XML::LibXML</a>, <a href="./HTML::TokeParser.html">HTML::TokeParser</a> and <a href="./HTML::TreeBuilder.html">HTML::TreeBuilder</a> modules are good starts, although each namespace has other parsing modules specialized for certain tasks and different ways of doing it. Start at CPAN Search ( <a href="http://metacpan.org/">http://metacpan.org/</a> ) and wonder at all the work people have done for you already! :)</p>

<h2 id="I-put-a-regular-expression-into-$/-but-it-didn&#39;t-work.-What&#39;s-wrong?"><a class="permalink" href="perlfaq6.html#I-put-a-regular-expression-into-$/-but-it-didn&#39;t-work.-What&#39;s-wrong?">#</a><a id="I1"></a><a id="I-put-a-regular-expression-into-but-it-didnt-work.-Whats-wrong"></a>I put a regular expression into $/ but it didn&#39;t work. What&#39;s wrong?   </h2>

<p>$/ has to be a string. You can use these examples if you really need to do this.</p>

<p>If you have <a href="./File::Stream.html">File::Stream</a>, this is easy.</p>

<pre><code>use File::Stream;

my $stream = File::Stream-&gt;new(
    $filehandle,
    separator =&gt; qr/\s*,\s*/,
    );

print &quot;$_\n&quot; while &lt;$stream&gt;;</code></pre>

<p>If you don&#39;t have File::Stream, you have to do a little more work.</p>

<p>You can use the four-argument form of sysread to continually add to a buffer. After you add to the buffer, you check if you have a complete line (using your regular expression).</p>

<pre><code>local $_ = &quot;&quot;;
while( sysread FH, $_, 8192, length ) {
    while( s/^((?s).*?)your_pattern// ) {
        my $record = $1;
        # do stuff here.
    }
}</code></pre>

<p>You can do the same thing with foreach and a match using the c flag and the \G anchor, if you do not mind your entire file being in memory at the end.</p>

<pre><code>local $_ = &quot;&quot;;
while( sysread FH, $_, 8192, length ) {
    foreach my $record ( m/\G((?s).*?)your_pattern/gc ) {
        # do stuff here.
    }
    substr( $_, 0, pos ) = &quot;&quot; if pos;
}</code></pre>

<h2 id="How-do-I-substitute-case-insensitively-on-the-LHS-while-preserving-case-on-the-RHS?"><a class="permalink" href="perlfaq6.html#How-do-I-substitute-case-insensitively-on-the-LHS-while-preserving-case-on-the-RHS?">#</a><a id="How3"></a><a id="How-do-I-substitute-case-insensitively-on-the-LHS-while-preserving-case-on-the-RHS"></a>How do I substitute case-insensitively on the LHS while preserving case on the RHS?    </h2>

<p>Here&#39;s a lovely Perlish solution by Larry Rosler. It exploits properties of bitwise xor on ASCII strings.</p>

<pre><code>$_= &quot;this is a TEsT case&quot;;

$old = &#39;test&#39;;
$new = &#39;success&#39;;

s{(\Q$old\E)}
{ uc $new | (uc $1 ^ $1) .
    (uc(substr $1, -1) ^ substr $1, -1) x
    (length($new) - length $1)
}egi;

print;</code></pre>

<p>And here it is as a subroutine, modeled after the above:</p>

<pre><code>sub preserve_case {
    my ($old, $new) = @_;
    my $mask = uc $old ^ $old;

    uc $new | $mask .
        substr($mask, -1) x (length($new) - length($old))
}

$string = &quot;this is a TEsT case&quot;;
$string =~ s/(test)/preserve_case($1, &quot;success&quot;)/egi;
print &quot;$string\n&quot;;</code></pre>

<p>This prints:</p>

<pre><code class="plaintext">this is a SUcCESS case</code></pre>

<p>As an alternative, to keep the case of the replacement word if it is longer than the original, you can use this code, by Jeff Pinyan:</p>

<pre><code>sub preserve_case {
    my ($from, $to) = @_;
    my ($lf, $lt) = map length, @_;

    if ($lt &lt; $lf) { $from = substr $from, 0, $lt }
    else { $from .= substr $to, $lf }

    return uc $to | ($from ^ uc $from);
}</code></pre>

<p>This changes the sentence to &quot;this is a SUcCess case.&quot;</p>

<p>Just to show that C programmers can write C in any programming language, if you prefer a more C-like solution, the following script makes the substitution have the same case, letter by letter, as the original. (It also happens to run about 240% slower than the Perlish solution runs.) If the substitution has more characters than the string being substituted, the case of the last character is used for the rest of the substitution.</p>

<pre><code># Original by Nathan Torkington, massaged by Jeffrey Friedl
#
sub preserve_case
{
    my ($old, $new) = @_;
    my $state = 0; # 0 = no change; 1 = lc; 2 = uc
    my ($i, $oldlen, $newlen, $c) = (0, length($old), length($new));
    my $len = $oldlen &lt; $newlen ? $oldlen : $newlen;

    for ($i = 0; $i &lt; $len; $i++) {
        if ($c = substr($old, $i, 1), $c =~ /[\W\d_]/) {
            $state = 0;
        } elsif (lc $c eq $c) {
            substr($new, $i, 1) = lc(substr($new, $i, 1));
            $state = 1;
        } else {
            substr($new, $i, 1) = uc(substr($new, $i, 1));
            $state = 2;
        }
    }
    # finish up with any remaining new (for when new is longer than old)
    if ($newlen &gt; $oldlen) {
        if ($state == 1) {
            substr($new, $oldlen) = lc(substr($new, $oldlen));
        } elsif ($state == 2) {
            substr($new, $oldlen) = uc(substr($new, $oldlen));
        }
    }
    return $new;
}</code></pre>

<h2 id="How-can-I-make-\w-match-national-character-sets?"><a class="permalink" href="perlfaq6.html#How-can-I-make-%5Cw-match-national-character-sets?">#</a><a id="How4"></a><a id="How-can-I-make-w-match-national-character-sets"></a>How can I make <code>\w</code> match national character sets? </h2>

<p>Put <code>use locale;</code> in your script. The \w character class is taken from the current locale.</p>

<p>See <a href="perllocale.html">perllocale</a> for details.</p>

<h2 id="How-can-I-match-a-locale-smart-version-of-/[a-zA-Z]/?"><a class="permalink" href="perlfaq6.html#How-can-I-match-a-locale-smart-version-of-/%5Ba-zA-Z%5D/?">#</a><a id="How5"></a><a id="How-can-I-match-a-locale-smart-version-of-a-zA-Z"></a>How can I match a locale-smart version of <code>/[a-zA-Z]/</code>? </h2>

<p>You can use the POSIX character class syntax <code>/[[:alpha:]]/</code> documented in <a href="perlre.html">perlre</a>.</p>

<p>No matter which locale you are in, the alphabetic characters are the characters in \w without the digits and the underscore. As a regex, that looks like <code>/[^\W\d_]/</code>. Its complement, the non-alphabetics, is then everything in \W along with the digits and the underscore, or <code>/[\W\d_]/</code>.</p>

<h2 id="How-can-I-quote-a-variable-to-use-in-a-regex?"><a class="permalink" href="perlfaq6.html#How-can-I-quote-a-variable-to-use-in-a-regex?">#</a><a id="How6"></a><a id="How-can-I-quote-a-variable-to-use-in-a-regex"></a>How can I quote a variable to use in a regex?   </h2>

<p>The Perl parser will expand $variable and @variable references in regular expressions unless the delimiter is a single quote. Remember, too, that the right-hand side of a <code>s///</code> substitution is considered a double-quoted string (see <a href="perlop.html">perlop</a> for more details). Remember also that any regex special characters will be acted on unless you precede the substitution with \Q. Here&#39;s an example:</p>

<pre><code>$string = &quot;Placido P. Octopus&quot;;
$regex  = &quot;P.&quot;;

$string =~ s/$regex/Polyp/;
# $string is now &quot;Polypacido P. Octopus&quot;</code></pre>

<p>Because <code>.</code> is special in regular expressions, and can match any single character, the regex <code>P.</code> here has matched the &lt;Pl&gt; in the original string.</p>

<p>To escape the special meaning of <code>.</code>, we use <code>\Q</code>:</p>

<pre><code>$string = &quot;Placido P. Octopus&quot;;
$regex  = &quot;P.&quot;;

$string =~ s/\Q$regex/Polyp/;
# $string is now &quot;Placido Polyp Octopus&quot;</code></pre>

<p>The use of <code>\Q</code> causes the <code>.</code> in the regex to be treated as a regular character, so that <code>P.</code> matches a <code>P</code> followed by a dot.</p>

<h2 id="What-is-/o-really-for?"><a class="permalink" href="perlfaq6.html#What-is-/o-really-for?">#</a><a id="What"></a><a id="What-is-o-really-for"></a>What is <code>/o</code> really for?  </h2>

<p>(contributed by brian d foy)</p>

<p>The <code>/o</code> option for regular expressions (documented in <a href="perlop.html">perlop</a> and <a href="perlreref.html">perlreref</a>) tells Perl to compile the regular expression only once. This is only useful when the pattern contains a variable. Perls 5.6 and later handle this automatically if the pattern does not change.</p>

<p>Since the match operator <code>m//</code>, the substitution operator <code>s///</code>, and the regular expression quoting operator <code>qr//</code> are double-quotish constructs, you can interpolate variables into the pattern. See the answer to &quot;How can I quote a variable to use in a regex?&quot; for more details.</p>

<p>This example takes a regular expression from the argument list and prints the lines of input that match it:</p>

<pre><code>my $pattern = shift @ARGV;

while( &lt;&gt; ) {
    print if m/$pattern/;
}</code></pre>

<p>Versions of Perl prior to 5.6 would recompile the regular expression for each iteration, even if <code>$pattern</code> had not changed. The <code>/o</code> would prevent this by telling Perl to compile the pattern the first time, then reuse that for subsequent iterations:</p>

<pre><code>my $pattern = shift @ARGV;

while( &lt;&gt; ) {
    print if m/$pattern/o; # useful for Perl &lt; 5.6
}</code></pre>

<p>In versions 5.6 and later, Perl won&#39;t recompile the regular expression if the variable hasn&#39;t changed, so you probably don&#39;t need the <code>/o</code> option. It doesn&#39;t hurt, but it doesn&#39;t help either. If you want any version of Perl to compile the regular expression only once even if the variable changes (thus, only using its initial value), you still need the <code>/o</code>.</p>

<p>You can watch Perl&#39;s regular expression engine at work to verify for yourself if Perl is recompiling a regular expression. The <code>use re &#39;debug&#39;</code> pragma (comes with Perl 5.005 and later) shows the details. With Perls before 5.6, you should see <code>re</code> reporting that its compiling the regular expression on each iteration. With Perl 5.6 or later, you should only see <code>re</code> report that for the first iteration.</p>

<pre><code>use re &#39;debug&#39;;

my $regex = &#39;Perl&#39;;
foreach ( qw(Perl Java Ruby Python) ) {
    print STDERR &quot;-&quot; x 73, &quot;\n&quot;;
    print STDERR &quot;Trying $_...\n&quot;;
    print STDERR &quot;\t$_ is good!\n&quot; if m/$regex/;
}</code></pre>

<h2 id="How-do-I-use-a-regular-expression-to-strip-C-style-comments-from-a-file?"><a class="permalink" href="perlfaq6.html#How-do-I-use-a-regular-expression-to-strip-C-style-comments-from-a-file?">#</a><a id="How7"></a><a id="How-do-I-use-a-regular-expression-to-strip-C-style-comments-from-a-file"></a>How do I use a regular expression to strip C-style comments from a file?</h2>

<p>While this actually can be done, it&#39;s much harder than you&#39;d think. For example, this one-liner</p>

<pre><code class="plaintext">perl -0777 -pe &#39;s{/\*.*?\*/}{}gs&#39; foo.c</code></pre>

<p>will work in many but not all cases. You see, it&#39;s too simple-minded for certain kinds of C programs, in particular, those with what appear to be comments in quoted strings. For that, you&#39;d need something like this, created by Jeffrey Friedl and later modified by Fred Curtis.</p>

<pre><code>$/ = undef;
$_ = &lt;&gt;;
s#/\*[^*]*\*+([^/*][^*]*\*+)*/|(&quot;(\\.|[^&quot;\\])*&quot;|&#39;(\\.|[^&#39;\\])*&#39;|.[^/&quot;&#39;\\]*)#defined $2 ? $2 : &quot;&quot;#gse;
print;</code></pre>

<p>This could, of course, be more legibly written with the <code>/x</code> modifier, adding whitespace and comments. Here it is expanded, courtesy of Fred Curtis.</p>

<pre><code>s{
   /\*         ##  Start of /* ... */ comment
   [^*]*\*+    ##  Non-* followed by 1-or-more *&#39;s
   (
     [^/*][^*]*\*+
   )*          ##  0-or-more things which don&#39;t start with /
               ##    but do end with &#39;*&#39;
   /           ##  End of /* ... */ comment

 |         ##     OR  various things which aren&#39;t comments:

   (
     &quot;           ##  Start of &quot; ... &quot; string
     (
       \\.           ##  Escaped char
     |               ##    OR
       [^&quot;\\]        ##  Non &quot;\
     )*
     &quot;           ##  End of &quot; ... &quot; string

   |         ##     OR

     &#39;           ##  Start of &#39; ... &#39; string
     (
       \\.           ##  Escaped char
     |               ##    OR
       [^&#39;\\]        ##  Non &#39;\
     )*
     &#39;           ##  End of &#39; ... &#39; string

   |         ##     OR

     .           ##  Anything other char
     [^/&quot;&#39;\\]*   ##  Chars which doesn&#39;t start a comment, string or escape
   )
 }{defined $2 ? $2 : &quot;&quot;}gxse;</code></pre>

<p>A slight modification also removes C++ comments, possibly spanning multiple lines using a continuation character:</p>

<pre><code>s#/\*[^*]*\*+([^/*][^*]*\*+)*/|//([^\\]|[^\n][\n]?)*?\n|(&quot;(\\.|[^&quot;\\])*&quot;|&#39;(\\.|[^&#39;\\])*&#39;|.[^/&quot;&#39;\\]*)#defined $3 ? $3 : &quot;&quot;#gse;</code></pre>

<h2 id="Can-I-use-Perl-regular-expressions-to-match-balanced-text?"><a class="permalink" href="perlfaq6.html#Can-I-use-Perl-regular-expressions-to-match-balanced-text?">#</a><a id="Can"></a><a id="Can-I-use-Perl-regular-expressions-to-match-balanced-text"></a>Can I use Perl regular expressions to match balanced text?         </h2>

<p>(contributed by brian d foy)</p>

<p>Your first try should probably be the <a href="./Text::Balanced.html">Text::Balanced</a> module, which is in the Perl standard library since Perl 5.8. It has a variety of functions to deal with tricky text. The <a href="./Regexp::Common.html">Regexp::Common</a> module can also help by providing canned patterns you can use.</p>

<p>As of Perl 5.10, you can match balanced text with regular expressions using recursive patterns. Before Perl 5.10, you had to resort to various tricks such as using Perl code in <code>(??{})</code> sequences.</p>

<p>Here&#39;s an example using a recursive regular expression. The goal is to capture all of the text within angle brackets, including the text in nested angle brackets. This sample text has two &quot;major&quot; groups: a group with one level of nesting and a group with two levels of nesting. There are five total groups in angle brackets:</p>

<pre><code class="plaintext">I have some &lt;brackets in &lt;nested brackets&gt; &gt; and
&lt;another group &lt;nested once &lt;nested twice&gt; &gt; &gt;
and that&#39;s it.</code></pre>

<p>The regular expression to match the balanced text uses two new (to Perl 5.10) regular expression features. These are covered in <a href="perlre.html">perlre</a> and this example is a modified version of one in that documentation.</p>

<p>First, adding the new possessive <code>+</code> to any quantifier finds the longest match and does not backtrack. That&#39;s important since you want to handle any angle brackets through the recursion, not backtracking. The group <code>[^&lt;&gt;]++</code> finds one or more non-angle brackets without backtracking.</p>

<p>Second, the new <code>(?PARNO)</code> refers to the sub-pattern in the particular capture group given by <code>PARNO</code>. In the following regex, the first capture group finds (and remembers) the balanced text, and you need that same pattern within the first buffer to get past the nested text. That&#39;s the recursive part. The <code>(?1)</code> uses the pattern in the outer capture group as an independent part of the regex.</p>

<p>Putting it all together, you have:</p>

<pre><code>#!/usr/local/bin/perl5.10.0

my $string =&lt;&lt;&quot;HERE&quot;;
I have some &lt;brackets in &lt;nested brackets&gt; &gt; and
&lt;another group &lt;nested once &lt;nested twice&gt; &gt; &gt;
and that&#39;s it.
HERE

my @groups = $string =~ m/
        (                   # start of capture group 1
        &lt;                   # match an opening angle bracket
            (?:
                [^&lt;&gt;]++     # one or more non angle brackets, non backtracking
                  |
                (?1)        # found &lt; or &gt;, so recurse to capture group 1
            )*
        &gt;                   # match a closing angle bracket
        )                   # end of capture group 1
        /xg;

$&quot; = &quot;\n\t&quot;;
print &quot;Found:\n\t@groups\n&quot;;</code></pre>

<p>The output shows that Perl found the two major groups:</p>

<pre><code class="plaintext">Found:
    &lt;brackets in &lt;nested brackets&gt; &gt;
    &lt;another group &lt;nested once &lt;nested twice&gt; &gt; &gt;</code></pre>

<p>With a little extra work, you can get all of the groups in angle brackets even if they are in other angle brackets too. Each time you get a balanced match, remove its outer delimiter (that&#39;s the one you just matched so don&#39;t match it again) and add it to a queue of strings to process. Keep doing that until you get no matches:</p>

<pre><code>#!/usr/local/bin/perl5.10.0

my @queue =&lt;&lt;&quot;HERE&quot;;
I have some &lt;brackets in &lt;nested brackets&gt; &gt; and
&lt;another group &lt;nested once &lt;nested twice&gt; &gt; &gt;
and that&#39;s it.
HERE

my $regex = qr/
        (                   # start of bracket 1
        &lt;                   # match an opening angle bracket
            (?:
                [^&lt;&gt;]++     # one or more non angle brackets, non backtracking
                  |
                (?1)        # recurse to bracket 1
            )*
        &gt;                   # match a closing angle bracket
        )                   # end of bracket 1
        /x;

$&quot; = &quot;\n\t&quot;;

while( @queue ) {
    my $string = shift @queue;

    my @groups = $string =~ m/$regex/g;
    print &quot;Found:\n\t@groups\n\n&quot; if @groups;

    unshift @queue, map { s/^&lt;//; s/&gt;$//; $_ } @groups;
}</code></pre>

<p>The output shows all of the groups. The outermost matches show up first and the nested matches show up later:</p>

<pre><code class="plaintext">Found:
    &lt;brackets in &lt;nested brackets&gt; &gt;
    &lt;another group &lt;nested once &lt;nested twice&gt; &gt; &gt;

Found:
    &lt;nested brackets&gt;

Found:
    &lt;nested once &lt;nested twice&gt; &gt;

Found:
    &lt;nested twice&gt;</code></pre>

<h2 id="What-does-it-mean-that-regexes-are-greedy?-How-can-I-get-around-it?"><a class="permalink" href="perlfaq6.html#What-does-it-mean-that-regexes-are-greedy?-How-can-I-get-around-it?">#</a><a id="What1"></a><a id="What-does-it-mean-that-regexes-are-greedy-How-can-I-get-around-it"></a>What does it mean that regexes are greedy? How can I get around it?  </h2>

<p>Most people mean that greedy regexes match as much as they can. Technically speaking, it&#39;s actually the quantifiers (<code>?</code>, <code>*</code>, <code>+</code>, <code>{}</code>) that are greedy rather than the whole pattern; Perl prefers local greed and immediate gratification to overall greed. To get non-greedy versions of the same quantifiers, use (<code>??</code>, <code>*?</code>, <code>+?</code>, <code>{}?</code>).</p>

<p>An example:</p>

<pre><code>my $s1 = my $s2 = &quot;I am very very cold&quot;;
$s1 =~ s/ve.*y //;      # I am cold
$s2 =~ s/ve.*?y //;     # I am very cold</code></pre>

<p>Notice how the second substitution stopped matching as soon as it encountered &quot;y &quot;. The <code>*?</code> quantifier effectively tells the regular expression engine to find a match as quickly as possible and pass control on to whatever is next in line, as you would if you were playing hot potato.</p>

<h2 id="How-do-I-process-each-word-on-each-line?"><a class="permalink" href="perlfaq6.html#How-do-I-process-each-word-on-each-line?">#</a><a id="How8"></a><a id="How-do-I-process-each-word-on-each-line"></a>How do I process each word on each line? </h2>

<p>Use the split function:</p>

<pre><code>while (&lt;&gt;) {
    foreach my $word ( split ) {
        # do something with $word here
    }
}</code></pre>

<p>Note that this isn&#39;t really a word in the English sense; it&#39;s just chunks of consecutive non-whitespace characters.</p>

<p>To work with only alphanumeric sequences (including underscores), you might consider</p>

<pre><code>while (&lt;&gt;) {
    foreach $word (m/(\w+)/g) {
        # do something with $word here
    }
}</code></pre>

<h2 id="How-can-I-print-out-a-word-frequency-or-line-frequency-summary?"><a class="permalink" href="perlfaq6.html#How-can-I-print-out-a-word-frequency-or-line-frequency-summary?">#</a><a id="How9"></a><a id="How-can-I-print-out-a-word-frequency-or-line-frequency-summary"></a>How can I print out a word-frequency or line-frequency summary?</h2>

<p>To do this, you have to parse out each word in the input stream. We&#39;ll pretend that by word you mean chunk of alphabetics, hyphens, or apostrophes, rather than the non-whitespace chunk idea of a word given in the previous question:</p>

<pre><code>my (%seen);
while (&lt;&gt;) {
    while ( /(\b[^\W_\d][\w&#39;-]+\b)/g ) {   # misses &quot;`sheep&#39;&quot;
        $seen{$1}++;
    }
}

while ( my ($word, $count) = each %seen ) {
    print &quot;$count $word\n&quot;;
}</code></pre>

<p>If you wanted to do the same thing for lines, you wouldn&#39;t need a regular expression:</p>

<pre><code>my (%seen);

while (&lt;&gt;) {
    $seen{$_}++;
}

while ( my ($line, $count) = each %seen ) {
    print &quot;$count $line&quot;;
}</code></pre>

<p>If you want these output in a sorted order, see <a href="perlfaq4.html">perlfaq4</a>: &quot;How do I sort a hash (optionally by value instead of key)?&quot;.</p>

<h2 id="How-can-I-do-approximate-matching?"><a class="permalink" href="perlfaq6.html#How-can-I-do-approximate-matching?">#</a><a id="How10"></a><a id="How-can-I-do-approximate-matching"></a>How can I do approximate matching?  </h2>

<p>See the module <a href="./String::Approx.html">String::Approx</a> available from CPAN.</p>

<h2 id="How-do-I-efficiently-match-many-regular-expressions-at-once?"><a class="permalink" href="perlfaq6.html#How-do-I-efficiently-match-many-regular-expressions-at-once?">#</a><a id="How11"></a><a id="How-do-I-efficiently-match-many-regular-expressions-at-once"></a>How do I efficiently match many regular expressions at once?   </h2>

<p>(contributed by brian d foy)</p>

<p>You want to avoid compiling a regular expression every time you want to match it. In this example, perl must recompile the regular expression for every iteration of the <code>foreach</code> loop since <code>$pattern</code> can change:</p>

<pre><code>my @patterns = qw( fo+ ba[rz] );

LINE: while( my $line = &lt;&gt; ) {
    foreach my $pattern ( @patterns ) {
        if( $line =~ m/\b$pattern\b/i ) {
            print $line;
            next LINE;
        }
    }
}</code></pre>

<p>The <code>qr//</code> operator compiles a regular expression, but doesn&#39;t apply it. When you use the pre-compiled version of the regex, perl does less work. In this example, I inserted a <code>map</code> to turn each pattern into its pre-compiled form. The rest of the script is the same, but faster:</p>

<pre><code>my @patterns = map { qr/\b$_\b/i } qw( fo+ ba[rz] );

LINE: while( my $line = &lt;&gt; ) {
    foreach my $pattern ( @patterns ) {
        if( $line =~ m/$pattern/ ) {
            print $line;
            next LINE;
        }
    }
}</code></pre>

<p>In some cases, you may be able to make several patterns into a single regular expression. Beware of situations that require backtracking though. In this example, the regex is only compiled once because <code>$regex</code> doesn&#39;t change between iterations:</p>

<pre><code>my $regex = join &#39;|&#39;, qw( fo+ ba[rz] );

while( my $line = &lt;&gt; ) {
    print if $line =~ m/\b(?:$regex)\b/i;
}</code></pre>

<p>The function <a href="./Data::Munge.html#list2re">&quot;list2re&quot; in Data::Munge</a> on CPAN can also be used to form a single regex that matches a list of literal strings (not regexes).</p>

<p>For more details on regular expression efficiency, see <i>Mastering Regular Expressions</i> by Jeffrey Friedl. He explains how the regular expressions engine works and why some patterns are surprisingly inefficient. Once you understand how perl applies regular expressions, you can tune them for individual situations.</p>

<h2 id="Why-don&#39;t-word-boundary-searches-with-\b-work-for-me?"><a class="permalink" href="perlfaq6.html#Why-don&#39;t-word-boundary-searches-with-%5Cb-work-for-me?">#</a><a id="Why"></a><a id="Why-dont-word-boundary-searches-with-b-work-for-me"></a>Why don&#39;t word-boundary searches with <code>\b</code> work for me? </h2>

<p>(contributed by brian d foy)</p>

<p>Ensure that you know what \b really does: it&#39;s the boundary between a word character, \w, and something that isn&#39;t a word character. That thing that isn&#39;t a word character might be \W, but it can also be the start or end of the string.</p>

<p>It&#39;s not (not!) the boundary between whitespace and non-whitespace, and it&#39;s not the stuff between words we use to create sentences.</p>

<p>In regex speak, a word boundary (\b) is a &quot;zero width assertion&quot;, meaning that it doesn&#39;t represent a character in the string, but a condition at a certain position.</p>

<p>For the regular expression, /\bPerl\b/, there has to be a word boundary before the &quot;P&quot; and after the &quot;l&quot;. As long as something other than a word character precedes the &quot;P&quot; and succeeds the &quot;l&quot;, the pattern will match. These strings match /\bPerl\b/.</p>

<pre><code class="plaintext">&quot;Perl&quot;    # no word char before &quot;P&quot; or after &quot;l&quot;
&quot;Perl &quot;   # same as previous (space is not a word char)
&quot;&#39;Perl&#39;&quot;  # the &quot;&#39;&quot; char is not a word char
&quot;Perl&#39;s&quot;  # no word char before &quot;P&quot;, non-word char after &quot;l&quot;</code></pre>

<p>These strings do not match /\bPerl\b/.</p>

<pre><code class="plaintext">&quot;Perl_&quot;   # &quot;_&quot; is a word char!
&quot;Perler&quot;  # no word char before &quot;P&quot;, but one after &quot;l&quot;</code></pre>

<p>You don&#39;t have to use \b to match words though. You can look for non-word characters surrounded by word characters. These strings match the pattern /\b&#39;\b/.</p>

<pre><code class="plaintext">&quot;don&#39;t&quot;   # the &quot;&#39;&quot; char is surrounded by &quot;n&quot; and &quot;t&quot;
&quot;qep&#39;a&#39;&quot;  # the &quot;&#39;&quot; char is surrounded by &quot;p&quot; and &quot;a&quot;</code></pre>

<p>These strings do not match /\b&#39;\b/.</p>

<pre><code class="plaintext">&quot;foo&#39;&quot;    # there is no word char after non-word &quot;&#39;&quot;</code></pre>

<p>You can also use the complement of \b, \B, to specify that there should not be a word boundary.</p>

<p>In the pattern /\Bam\B/, there must be a word character before the &quot;a&quot; and after the &quot;m&quot;. These patterns match /\Bam\B/:</p>

<pre><code class="plaintext">&quot;llama&quot;   # &quot;am&quot; surrounded by word chars
&quot;Samuel&quot;  # same</code></pre>

<p>These strings do not match /\Bam\B/</p>

<pre><code class="plaintext">&quot;Sam&quot;      # no word boundary before &quot;a&quot;, but one after &quot;m&quot;
&quot;I am Sam&quot; # &quot;am&quot; surrounded by non-word chars</code></pre>

<h2 id="Why-does-using-$&amp;,-$`,-or-$&#39;-slow-my-program-down?"><a class="permalink" href="perlfaq6.html#Why-does-using-$&amp;,-$%60,-or-$&#39;-slow-my-program-down?">#</a><a id="Why1"></a><a id="Why-does-using-or-slow-my-program-down"></a>Why does using $&amp;, $`, or $&#39; slow my program down?      </h2>

<p>(contributed by Anno Siegel)</p>

<p>Once Perl sees that you need one of these variables anywhere in the program, it provides them on each and every pattern match. That means that on every pattern match the entire string will be copied, part of it to $`, part to $&amp;, and part to $&#39;. Thus the penalty is most severe with long strings and patterns that match often. Avoid $&amp;, $&#39;, and $` if you can, but if you can&#39;t, once you&#39;ve used them at all, use them at will because you&#39;ve already paid the price. Remember that some algorithms really appreciate them. As of the 5.005 release, the $&amp; variable is no longer &quot;expensive&quot; the way the other two are.</p>

<p>Since Perl 5.6.1 the special variables @- and @+ can functionally replace $`, $&amp; and $&#39;. These arrays contain pointers to the beginning and end of each match (see perlvar for the full story), so they give you essentially the same information, but without the risk of excessive string copying.</p>

<p>Perl 5.10 added three specials, <code>${^MATCH}</code>, <code>${^PREMATCH}</code>, and <code>${^POSTMATCH}</code> to do the same job but without the global performance penalty. Perl 5.10 only sets these variables if you compile or execute the regular expression with the <code>/p</code> modifier.</p>

<h2 id="What-good-is-\G-in-a-regular-expression?"><a class="permalink" href="perlfaq6.html#What-good-is-%5CG-in-a-regular-expression?">#</a><a id="What2"></a><a id="What-good-is-G-in-a-regular-expression"></a>What good is <code>\G</code> in a regular expression? </h2>

<p>You use the <code>\G</code> anchor to start the next match on the same string where the last match left off. The regular expression engine cannot skip over any characters to find the next match with this anchor, so <code>\G</code> is similar to the beginning of string anchor, <code>^</code>. The <code>\G</code> anchor is typically used with the <code>g</code> modifier. It uses the value of <code>pos()</code> as the position to start the next match. As the match operator makes successive matches, it updates <code>pos()</code> with the position of the next character past the last match (or the first character of the next match, depending on how you like to look at it). Each string has its own <code>pos()</code> value.</p>

<p>Suppose you want to match all of consecutive pairs of digits in a string like &quot;1122a44&quot; and stop matching when you encounter non-digits. You want to match <code>11</code> and <code>22</code> but the letter <code>a</code> shows up between <code>22</code> and <code>44</code> and you want to stop at <code>a</code>. Simply matching pairs of digits skips over the <code>a</code> and still matches <code>44</code>.</p>

<pre><code>$_ = &quot;1122a44&quot;;
my @pairs = m/(\d\d)/g;   # qw( 11 22 44 )</code></pre>

<p>If you use the <code>\G</code> anchor, you force the match after <code>22</code> to start with the <code>a</code>. The regular expression cannot match there since it does not find a digit, so the next match fails and the match operator returns the pairs it already found.</p>

<pre><code>$_ = &quot;1122a44&quot;;
my @pairs = m/\G(\d\d)/g; # qw( 11 22 )</code></pre>

<p>You can also use the <code>\G</code> anchor in scalar context. You still need the <code>g</code> modifier.</p>

<pre><code>$_ = &quot;1122a44&quot;;
while( m/\G(\d\d)/g ) {
    print &quot;Found $1\n&quot;;
}</code></pre>

<p>After the match fails at the letter <code>a</code>, perl resets <code>pos()</code> and the next match on the same string starts at the beginning.</p>

<pre><code>$_ = &quot;1122a44&quot;;
while( m/\G(\d\d)/g ) {
    print &quot;Found $1\n&quot;;
}

print &quot;Found $1 after while&quot; if m/(\d\d)/g; # finds &quot;11&quot;</code></pre>

<p>You can disable <code>pos()</code> resets on fail with the <code>c</code> modifier, documented in <a href="perlop.html">perlop</a> and <a href="perlreref.html">perlreref</a>. Subsequent matches start where the last successful match ended (the value of <code>pos()</code>) even if a match on the same string has failed in the meantime. In this case, the match after the <code>while()</code> loop starts at the <code>a</code> (where the last match stopped), and since it does not use any anchor it can skip over the <code>a</code> to find <code>44</code>.</p>

<pre><code>$_ = &quot;1122a44&quot;;
while( m/\G(\d\d)/gc ) {
    print &quot;Found $1\n&quot;;
}

print &quot;Found $1 after while&quot; if m/(\d\d)/g; # finds &quot;44&quot;</code></pre>

<p>Typically you use the <code>\G</code> anchor with the <code>c</code> modifier when you want to try a different match if one fails, such as in a tokenizer. Jeffrey Friedl offers this example which works in 5.004 or later.</p>

<pre><code>while (&lt;&gt;) {
    chomp;
    PARSER: {
        m/ \G( \d+\b    )/gcx   &amp;&amp; do { print &quot;number: $1\n&quot;;  redo; };
        m/ \G( \w+      )/gcx   &amp;&amp; do { print &quot;word:   $1\n&quot;;  redo; };
        m/ \G( \s+      )/gcx   &amp;&amp; do { print &quot;space:  $1\n&quot;;  redo; };
        m/ \G( [^\w\d]+ )/gcx   &amp;&amp; do { print &quot;other:  $1\n&quot;;  redo; };
    }
}</code></pre>

<p>For each line, the <code>PARSER</code> loop first tries to match a series of digits followed by a word boundary. This match has to start at the place the last match left off (or the beginning of the string on the first match). Since <code>m/ \G( \d+\b )/gcx</code> uses the <code>c</code> modifier, if the string does not match that regular expression, perl does not reset pos() and the next match starts at the same position to try a different pattern.</p>

<h2 id="Are-Perl-regexes-DFAs-or-NFAs?-Are-they-POSIX-compliant?"><a class="permalink" href="perlfaq6.html#Are-Perl-regexes-DFAs-or-NFAs?-Are-they-POSIX-compliant?">#</a><a id="Are"></a><a id="Are-Perl-regexes-DFAs-or-NFAs-Are-they-POSIX-compliant"></a>Are Perl regexes DFAs or NFAs? Are they POSIX compliant?   </h2>

<p>While it&#39;s true that Perl&#39;s regular expressions resemble the DFAs (deterministic finite automata) of the egrep(1) program, they are in fact implemented as NFAs (non-deterministic finite automata) to allow backtracking and backreferencing. And they aren&#39;t POSIX-style either, because those guarantee worst-case behavior for all cases. (It seems that some people prefer guarantees of consistency, even when what&#39;s guaranteed is slowness.) See the book &quot;Mastering Regular Expressions&quot; (from O&#39;Reilly) by Jeffrey Friedl for all the details you could ever hope to know on these matters (a full citation appears in <a href="perlfaq2.html">perlfaq2</a>).</p>

<h2 id="What&#39;s-wrong-with-using-grep-in-a-void-context?"><a class="permalink" href="perlfaq6.html#What&#39;s-wrong-with-using-grep-in-a-void-context?">#</a><a id="What3"></a><a id="Whats-wrong-with-using-grep-in-a-void-context"></a>What&#39;s wrong with using grep in a void context? </h2>

<p>The problem is that grep builds a return list, regardless of the context. This means you&#39;re making Perl go to the trouble of building a list that you then just throw away. If the list is large, you waste both time and space. If your intent is to iterate over the list, then use a for loop for this purpose.</p>

<p>In perls older than 5.8.1, map suffers from this problem as well. But since 5.8.1, this has been fixed, and map is context aware - in void context, no lists are constructed.</p>

<h2 id="How-can-I-match-strings-with-multibyte-characters?"><a class="permalink" href="perlfaq6.html#How-can-I-match-strings-with-multibyte-characters?">#</a><a id="How12"></a><a id="How-can-I-match-strings-with-multibyte-characters"></a>How can I match strings with multibyte characters?     </h2>

<p>Starting from Perl 5.6 Perl has had some level of multibyte character support. Perl 5.8 or later is recommended. Supported multibyte character repertoires include Unicode, and legacy encodings through the Encode module. See <a href="perluniintro.html">perluniintro</a>, <a href="perlunicode.html">perlunicode</a>, and <a href="Encode.html">Encode</a>.</p>

<p>If you are stuck with older Perls, you can do Unicode with the <a href="./Unicode::String.html">Unicode::String</a> module, and character conversions using the <a href="./Unicode::Map8.html">Unicode::Map8</a> and <a href="./Unicode::Map.html">Unicode::Map</a> modules. If you are using Japanese encodings, you might try using the jperl 5.005_03.</p>

<p>Finally, the following set of approaches was offered by Jeffrey Friedl, whose article in issue #5 of The Perl Journal talks about this very matter.</p>

<p>Let&#39;s suppose you have some weird Martian encoding where pairs of ASCII uppercase letters encode single Martian letters (i.e. the two bytes &quot;CV&quot; make a single Martian letter, as do the two bytes &quot;SG&quot;, &quot;VS&quot;, &quot;XX&quot;, etc.). Other bytes represent single characters, just like ASCII.</p>

<p>So, the string of Martian &quot;I am CVSGXX!&quot; uses 12 bytes to encode the nine characters &#39;I&#39;, &#39; &#39;, &#39;a&#39;, &#39;m&#39;, &#39; &#39;, &#39;CV&#39;, &#39;SG&#39;, &#39;XX&#39;, &#39;!&#39;.</p>

<p>Now, say you want to search for the single character <code>/GX/</code>. Perl doesn&#39;t know about Martian, so it&#39;ll find the two bytes &quot;GX&quot; in the &quot;I am CVSGXX!&quot; string, even though that character isn&#39;t there: it just looks like it is because &quot;SG&quot; is next to &quot;XX&quot;, but there&#39;s no real &quot;GX&quot;. This is a big problem.</p>

<p>Here are a few ways, all painful, to deal with it:</p>

<pre><code># Make sure adjacent &quot;martian&quot; bytes are no longer adjacent.
$martian =~ s/([A-Z][A-Z])/ $1 /g;

print &quot;found GX!\n&quot; if $martian =~ /GX/;</code></pre>

<p>Or like this:</p>

<pre><code>my @chars = $martian =~ m/([A-Z][A-Z]|[^A-Z])/g;
# above is conceptually similar to:     my @chars = $text =~ m/(.)/g;
#
foreach my $char (@chars) {
    print &quot;found GX!\n&quot;, last if $char eq &#39;GX&#39;;
}</code></pre>

<p>Or like this:</p>

<pre><code>while ($martian =~ m/\G([A-Z][A-Z]|.)/gs) {  # \G probably unneeded
    if ($1 eq &#39;GX&#39;) {
        print &quot;found GX!\n&quot;;
        last;
    }
}</code></pre>

<p>Here&#39;s another, slightly less painful, way to do it from Benjamin Goldberg, who uses a zero-width negative look-behind assertion.</p>

<pre><code>print &quot;found GX!\n&quot; if    $martian =~ m/
    (?&lt;![A-Z])
    (?:[A-Z][A-Z])*?
    GX
    /x;</code></pre>

<p>This succeeds if the &quot;martian&quot; character GX is in the string, and fails otherwise. If you don&#39;t like using (?&lt;!), a zero-width negative look-behind assertion, you can replace (?&lt;![A-Z]) with (?:^|[^A-Z]).</p>

<p>It does have the drawback of putting the wrong thing in $-[0] and $+[0], but this usually can be worked around.</p>

<h2 id="How-do-I-match-a-regular-expression-that&#39;s-in-a-variable?"><a class="permalink" href="perlfaq6.html#How-do-I-match-a-regular-expression-that&#39;s-in-a-variable?">#</a><a id="How13"></a><a id="How-do-I-match-a-regular-expression-thats-in-a-variable"></a>How do I match a regular expression that&#39;s in a variable?       </h2>

<p>(contributed by brian d foy)</p>

<p>We don&#39;t have to hard-code patterns into the match operator (or anything else that works with regular expressions). We can put the pattern in a variable for later use.</p>

<p>The match operator is a double quote context, so you can interpolate your variable just like a double quoted string. In this case, you read the regular expression as user input and store it in <code>$regex</code>. Once you have the pattern in <code>$regex</code>, you use that variable in the match operator.</p>

<pre><code>chomp( my $regex = &lt;STDIN&gt; );

if( $string =~ m/$regex/ ) { ... }</code></pre>

<p>Any regular expression special characters in <code>$regex</code> are still special, and the pattern still has to be valid or Perl will complain. For instance, in this pattern there is an unpaired parenthesis.</p>

<pre><code>my $regex = &quot;Unmatched ( paren&quot;;

&quot;Two parens to bind them all&quot; =~ m/$regex/;</code></pre>

<p>When Perl compiles the regular expression, it treats the parenthesis as the start of a memory match. When it doesn&#39;t find the closing parenthesis, it complains:</p>

<pre><code class="plaintext">Unmatched ( in regex; marked by &lt;-- HERE in m/Unmatched ( &lt;-- HERE  paren/ at script line 3.</code></pre>

<p>You can get around this in several ways depending on our situation. First, if you don&#39;t want any of the characters in the string to be special, you can escape them with <code>quotemeta</code> before you use the string.</p>

<pre><code>chomp( my $regex = &lt;STDIN&gt; );
$regex = quotemeta( $regex );

if( $string =~ m/$regex/ ) { ... }</code></pre>

<p>You can also do this directly in the match operator using the <code>\Q</code> and <code>\E</code> sequences. The <code>\Q</code> tells Perl where to start escaping special characters, and the <code>\E</code> tells it where to stop (see <a href="perlop.html">perlop</a> for more details).</p>

<pre><code>chomp( my $regex = &lt;STDIN&gt; );

if( $string =~ m/\Q$regex\E/ ) { ... }</code></pre>

<p>Alternately, you can use <code>qr//</code>, the regular expression quote operator (see <a href="perlop.html">perlop</a> for more details). It quotes and perhaps compiles the pattern, and you can apply regular expression flags to the pattern.</p>

<pre><code>chomp( my $input = &lt;STDIN&gt; );

my $regex = qr/$input/is;

$string =~ m/$regex/  # same as m/$input/is;</code></pre>

<p>You might also want to trap any errors by wrapping an <code>eval</code> block around the whole thing.</p>

<pre><code>chomp( my $input = &lt;STDIN&gt; );

eval {
    if( $string =~ m/\Q$input\E/ ) { ... }
};
warn $@ if $@;</code></pre>

<p>Or...</p>

<pre><code>my $regex = eval { qr/$input/is };
if( defined $regex ) {
    $string =~ m/$regex/;
}
else {
    warn $@;
}</code></pre>

<h1 id="AUTHOR-AND-COPYRIGHT"><a class="permalink" href="perlfaq6.html#AUTHOR-AND-COPYRIGHT">#</a><a id="AUTHOR"></a>AUTHOR AND COPYRIGHT</h1>

<p>Copyright (c) 1997-2010 Tom Christiansen, Nathan Torkington, and other authors as noted. All rights reserved.</p>

<p>This documentation is free; you can redistribute it and/or modify it under the same terms as Perl itself.</p>

<p>Irrespective of its distribution, all code examples in this file are hereby placed into the public domain. You are permitted and encouraged to use this code in your own programs for fun or for profit as you see fit. A simple comment in the code giving credit would be courteous but is not required.</p>


      </div>
      <div id="footer">
        <p>Perldoc Browser is maintained by Dan Book (<a href="https://metacpan.org/author/DBOOK">DBOOK</a>). Please contact him via the <a href="https://github.com/Grinnz/perldoc-browser/issues">GitHub issue tracker</a> or <a href="mailto:dbook@cpan.org">email</a> regarding any issues with the site itself, search, or rendering of documentation.</p>

<p>The Perl documentation is maintained by the Perl 5 Porters in the development of Perl. Please contact them via the <a href="https://github.com/Perl/perl5/issues">Perl issue tracker</a>, the <a href="https://lists.perl.org/list/perl5-porters.html">mailing list</a>, or <a href="https://kiwiirc.com/client/irc.perl.org/p5p">IRC</a> to report any issues with the contents or format of the documentation.</p>


      </div>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.slim.min.js" integrity="sha512-/DXTXr6nQodMUiq+IUJYCt2PPOUjrHJ9wFrqpJ3XkgPNOZVfMok7cRw6CSxyCQxXn6ozlESsSh1/sMCTF1rL/g==" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.1/umd/popper.min.js" integrity="sha512-ubuT8Z88WxezgSqf3RLuNi5lmjstiJcyezx34yIU2gAHonIi27Na7atqzUZCOoY4CExaoFumzOsFQ2Ch+I/HCw==" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
    <script src="../highlight.pack.js"></script>
    <script>hljs.highlightAll();</script>
  </body>
</html>
